const fs = require('fs')
const {
  v4: uuidv4
} = require('uuid');


async function getFileType(currentDir) {
  return new Promise((resolve, reject) => {
    fs.stat(currentDir, (err, data) => {
      if (!err) {
        resolve(data.isDirectory())
      }
    })
  })
}

async function getChildrenList(basePath, fileDir, flag) {
  let result = [];
  let _json = {
    id: uuidv4(),
    label: fileDir
  };
  let temp = []
  if (flag) {
    let currentDir = basePath + '/' + fileDir;
    const files = fs.readdirSync(currentDir);
    if (files.length > 0) {
      for (let i = 0; i < files.length; i++) {
        let fileType = await getFileType(currentDir + '/' + files[i]);
        temp = temp.concat(await getChildrenList(currentDir, files[i], fileType));
      }
      _json.children = temp
    }
  }
  result.push(_json)
  return result;
}

module.exports = {
  getChildrenList
}
